#!/usr/bin/env python3
"""
SaaS平台发布与回滚系统 - 启动脚本
"""
import os
import sys
import subprocess
import argparse
from pathlib import Path

def check_dependencies():
    """检查依赖"""
    print("检查系统依赖...")
    
    # 检查Python版本
    if sys.version_info < (3, 8):
        print("❌ 需要Python 3.8或更高版本")
        return False
    
    print(f"✅ Python版本: {sys.version}")
    
    # 检查必要的命令
    required_commands = ['pip', 'uvicorn']
    for cmd in required_commands:
        try:
            subprocess.run([cmd, '--version'], capture_output=True, check=True)
            print(f"✅ {cmd} 已安装")
        except (subprocess.CalledProcessError, FileNotFoundError):
            print(f"❌ {cmd} 未安装")
            return False
    
    return True

def install_dependencies():
    """安装依赖"""
    print("安装Python依赖...")
    
    try:
        subprocess.run([sys.executable, '-m', 'pip', 'install', '-r', 'requirements.txt'], check=True)
        print("✅ 依赖安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖安装失败: {e}")
        return False

def init_database():
    """初始化数据库"""
    print("初始化数据库...")
    
    try:
        # 运行数据库初始化脚本
        subprocess.run([sys.executable, 'scripts/init_data.py'], check=True)
        print("✅ 数据库初始化完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 数据库初始化失败: {e}")
        return False

def start_services(mode='dev'):
    """启动服务"""
    if mode == 'dev':
        print("启动开发模式...")
        print("启动API服务: http://localhost:8000")
        print("API文档: http://localhost:8000/docs")
        print("按 Ctrl+C 停止服务")
        
        try:
            subprocess.run([
                'uvicorn', 'app.main:app',
                '--host', '0.0.0.0',
                '--port', '8000',
                '--reload'
            ])
        except KeyboardInterrupt:
            print("\n服务已停止")
    
    elif mode == 'prod':
        print("启动生产模式...")
        print("使用Docker Compose启动所有服务")
        
        try:
            subprocess.run(['docker-compose', 'up', '-d'], check=True)
            print("✅ 服务启动完成")
            print("API服务: http://localhost:8000")
            print("监控面板: http://localhost:3000")
            print("Celery监控: http://localhost:5555")
        except subprocess.CalledProcessError as e:
            print(f"❌ 服务启动失败: {e}")

def stop_services():
    """停止服务"""
    print("停止服务...")
    
    try:
        subprocess.run(['docker-compose', 'down'], check=True)
        print("✅ 服务已停止")
    except subprocess.CalledProcessError as e:
        print(f"❌ 停止服务失败: {e}")

def check_services():
    """检查服务状态"""
    print("检查服务状态...")
    
    try:
        result = subprocess.run(['docker-compose', 'ps'], capture_output=True, text=True, check=True)
        print(result.stdout)
    except subprocess.CalledProcessError as e:
        print(f"❌ 检查服务状态失败: {e}")

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="SaaS平台发布与回滚系统 - 启动脚本")
    parser.add_argument('action', choices=['start', 'stop', 'restart', 'status', 'init'],
                       help='操作类型')
    parser.add_argument('--mode', '-m', choices=['dev', 'prod'], default='dev',
                       help='运行模式 (默认: dev)')
    parser.add_argument('--skip-deps', action='store_true',
                       help='跳过依赖检查')
    parser.add_argument('--skip-db', action='store_true',
                       help='跳过数据库初始化')
    
    args = parser.parse_args()
    
    print("SaaS平台发布与回滚系统")
    print("=" * 50)
    
    if args.action == 'init':
        # 初始化操作
        if not args.skip_deps:
            if not check_dependencies():
                sys.exit(1)
            if not install_dependencies():
                sys.exit(1)
        
        if not args.skip_db:
            if not init_database():
                sys.exit(1)
        
        print("✅ 初始化完成！")
        print("运行 'python start.py start' 启动服务")
    
    elif args.action == 'start':
        # 启动服务
        if args.mode == 'prod':
            start_services('prod')
        else:
            start_services('dev')
    
    elif args.action == 'stop':
        # 停止服务
        stop_services()
    
    elif args.action == 'restart':
        # 重启服务
        stop_services()
        start_services(args.mode)
    
    elif args.action == 'status':
        # 检查状态
        check_services()

if __name__ == "__main__":
    main()
